package com.example.test.dialogfactory;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;
import androidx.room.ColumnInfo;
import androidx.room.Dao;
import androidx.room.Database;
import androidx.room.Delete;
import androidx.room.Entity;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.PrimaryKey;
import androidx.room.Query;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import easier.recycler.BaseViewHolder;
import easier.recycler.MultiTypeAdapter;
import easier.recycler.TypeViewHolder;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.schedulers.Schedulers;
import java.util.ArrayList;
import java.util.List;

public class MainActivity53 extends AppCompatActivity {

    private static final String TAG = "MainActivity53";
    private EditText mInputFirst;
    private EditText mInputLast;
    private TextView mText;
    private Button mSave;
    private Button mRead;
    private Button mAll;
    private RecyclerView mRecycler;

    public static void start( Context context ) {

        Intent starter = new Intent( context, MainActivity53.class );
        context.startActivity( starter );
    }

    @Override
    protected void onCreate( Bundle savedInstanceState ) {

        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main53 );

        AppDataBase db = Room.databaseBuilder( getApplicationContext(), AppDataBase.class, "database" ).build();
        UserDao userDao = db.userDao();

        initView( userDao );
    }

    private void initView( UserDao userDao ) {

        mInputFirst = (EditText) findViewById( R.id.inputFirst );
        mInputLast = (EditText) findViewById( R.id.inputLast );
        mText = (TextView) findViewById( R.id.text );
        mSave = (Button) findViewById( R.id.save );
        mRead = (Button) findViewById( R.id.read );

        mSave.setOnClickListener( new OnClickListener() {
            @Override
            public void onClick( View v ) {

                Editable text = mInputFirst.getText();
                Editable text1 = mInputLast.getText();

                if ( !TextUtils.isEmpty( text1 ) && !TextUtils.isEmpty( text ) ) {

                    Observable.just( "" )
                        .subscribeOn( Schedulers.io() )
                        .subscribe( new Consumer< String >() {
                            @Override
                            public void accept( String s ) throws Throwable {

                                User user = new User();
                                user.firstName = text.toString();
                                user.lastName = text1.toString();

                                userDao.insertAll( user );
                            }
                        } );
                }
            }
        } );

        mRead.setOnClickListener( new OnClickListener() {
            @Override
            public void onClick( View v ) {

                Observable.just( "" )
                    .subscribeOn( Schedulers.io() )
                    .subscribe( new Consumer< String >() {
                        @Override
                        public void accept( String s ) throws Throwable {

                            int rowCount = userDao.getRowCount();
                            mText.post( new Runnable() {
                                @Override
                                public void run() {

                                    mText.setText( "总数据:" + rowCount + "条" );
                                }
                            } );
                        }
                    } );
            }
        } );

        mAll = (Button) findViewById( R.id.all );
        mRecycler = (RecyclerView) findViewById( R.id.recycler );
        mRecycler.setLayoutManager( new LinearLayoutManager( this ) );
        final MultiTypeAdapter adapter = new MultiTypeAdapter();
        mRecycler.setAdapter( adapter );

        mAll.setOnClickListener( new OnClickListener() {
            @Override
            public void onClick( View v ) {

                Observable.just( "" )
                    .subscribeOn( Schedulers.io() )
                    .map( new Function< String, List< User > >() {
                        @Override
                        public List< User > apply( String s ) throws Throwable {

                            return userDao.getAll();
                        }
                    } )
                    .observeOn( AndroidSchedulers.mainThread() )
                    .subscribe( new Consumer< List< User > >() {
                        @Override
                        public void accept( List< User > list ) throws Throwable {

                            List< TypeViewHolder > result = new ArrayList<>();
                            for ( User user : list ) {
                                result.add( new BaseViewHolder( R.layout.activity_main_53_item ) {

                                    @Override
                                    protected void onBind( ViewHolder viewHolder, View root, int position, int type, List< Object > payloads ) {

                                        super.onBind( viewHolder, root, position, type, payloads );

                                        TextView view = (TextView) root.findViewById( R.id.text );
                                        view.setText( user.toString() );
                                    }
                                } );
                            }
                            adapter.updateViewHolders( result );
                        }
                    } );
            }
        } );
    }

    @Entity( tableName = "user" )
    public static class User {

        @PrimaryKey( autoGenerate = true )
        public int uid;

        @ColumnInfo( name = "first_name" )
        public String firstName;

        @ColumnInfo( name = "last_name" )
        public String lastName;

        @Override
        public String toString() {

            return "User{" +
                "uid=" + uid +
                ", firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                '}';
        }
    }

    @Dao
    public interface UserDao {

        @Query( "SELECT * FROM user" )
        List< User > getAll();

        @Query( "select * from user where uid in (:userIds)" )
        List< User > loadAllByIds( int[] userIds );

        @Query( "select * from user where first_name like :first and last_name like :last" )
        User findByName( String first, String last );

        @Insert( onConflict = OnConflictStrategy.REPLACE )
        void insertAll( User... users );

        @Delete
        void delete( User user );

        @Query( "select count(uid) from user" )
        int getRowCount();
    }

    @Database( entities = User.class, version = 1, exportSchema = false )
    public static abstract class AppDataBase extends RoomDatabase {

        public abstract UserDao userDao();
    }
}